package com.ruoyi.web.controller.system;

import com.ruoyi.system.domain.MonitorRule;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.domain.ProjectAlarmRule;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/project.v2")
public class ProjectAlarmController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    IProjectAlarmRuleService projectAlarmRuleService;

    @Autowired
    IMonitorRuleService monitorRuleService;

    @Autowired
    IProjectService projectService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;

    private AjaxResult checkExistance(ProjectAlarmRule projectAlarmRule) {
        Map<String, Object> existance = projectAlarmRuleService.findExistance(projectAlarmRule);
        if (existance != null) {
            Object rule_exists = existance.get("rule_exists");
            if (rule_exists != null && Integer.parseInt(rule_exists.toString()) > 0) {
                return AjaxResult.error(HttpStatus.ERROR, "监控规则已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:add')")
    @PostMapping(value = "/alarm/rule/add", produces = "application/json;charset=UTF-8")
    @Log(title = "项目报警规则", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) ProjectAlarmRule projectAlarmRule) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectAlarmRule.getProjectId());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectAlarmRule.getProjectId());
        Project project = projectService.retrieve(queryVo);
        if (project == null) {
            return AjaxResult.error("没有找到指定的项目");
        }
        queryVo.filters.clear();
        queryVo.filters.put("id", projectAlarmRule.getMonitorRuleId());
        MonitorRule monitorRule = monitorRuleService.retrieve(queryVo);
        if (monitorRule == null) {
            return AjaxResult.error("没有找到指定的监控规则");
        }
        //LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        projectAlarmRule.setCompanyId(companyId);
        projectAlarmRule.setCreateBy(createBy);
        projectAlarmRule.setCreateTime(new Date());
        AjaxResult ret = checkExistance(projectAlarmRule);
        if (ret != null) {
            return ret;
        }
        Integer id = projectAlarmRuleService.create(projectAlarmRule);
        if (id != null) {
            return AjaxResult.success(projectAlarmRule);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:list')")
    @GetMapping(value = "/alarm/rule/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) ProjectAlarmRule projectAlarmRule) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectAlarmRule.getProjectId());
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id", projectAlarmRule.getProjectId());
        queryVo.filters.put("monitor_rule_id", projectAlarmRule.getMonitorRuleId());
        queryVo.filters.put("monitor_rule_name", projectAlarmRule.getMonitorRuleName());
        queryVo.filters.put("severity", projectAlarmRule.getSeverity());
        startPage();
        List<ProjectAlarmRule> projectAlarmRules = projectAlarmRuleService.index(queryVo);
        return getDataTable(projectAlarmRules);
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:available')")
    @GetMapping(value = "/alarm/rule/available", produces = "application/json;charset=UTF-8")
    public AjaxResult availableMonitorRuleList(@RequestParam("projectId") @NotNull(message = "项目id不能为null") Integer projectId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectId);
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id", projectId);
        List<Map<String, Object>> available = projectAlarmRuleService.available(queryVo);
        return AjaxResult.success(available);
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:query')")
    @GetMapping(value = "/alarm/rule/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProjectAlarmRule projectAlarmRule = projectAlarmRuleService.retrieve(queryVo);
        if (projectAlarmRule == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectAlarmRule.getProjectId());
        return AjaxResult.success(projectAlarmRule);
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:edit')")
    @Log(title = "项目报警规则", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/alarm/rule/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) ProjectAlarmRule projectAlarmRule) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectAlarmRule.getId());
        ProjectAlarmRule target = projectAlarmRuleService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),target.getProjectId());
        projectAlarmRule.setProjectId(target.getProjectId());
        projectAlarmRule.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(projectAlarmRule);
        if (ret != null) {
            return ret;
        }
        if (projectAlarmRuleService.update(projectAlarmRule)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:alarm:rule:remove')")
    @Log(title = "项目报警规则", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/alarm/rule/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProjectAlarmRule target = projectAlarmRuleService.retrieve(queryVo);
        if (target != null){
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),target.getProjectId());
        }
        if (projectAlarmRuleService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
